package com.xayy.mgt.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.kawins.base.result.ResultBody;
import cn.kawins.mybatis.base.BaseController;
import com.xayy.core.utils.FileUtils;
import com.xayy.mgt.model.FileInfo;
import com.xayy.mgt.model.NodeTreeInfo;
import com.xayy.mgt.service.FileInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.Date;
import java.util.UUID;

@Api(tags = "文件管理")
@RestController
@RequestMapping(value = "upload1")
@Slf4j
public class UploadController extends BaseController<NodeTreeInfo> {

    @Value("${file.upload.path}")
    public String fileUploadPath;
    @Value("${file.upload.relative}")
    public String fileUploadRelative;

    @Autowired
    private FileInfoService fileInfoService;
    @PostMapping(value = "/uploadFile")
    @ApiOperation(value = "上传文件",httpMethod = "POST",response = FileInfo.class,notes = "通用-上传文件功能")
    public ResultBody uploadFile(@RequestParam("file") MultipartFile file) {
        log.info("上传文件开始.....");
        FileInfo fileInfo = new FileInfo();
        if (ObjectUtil.isNotNull(file)) {
            try {
                String uid = UUID.randomUUID().toString();
                String fileName = file.getOriginalFilename();
                String fileSuffix = StrUtil.subAfter(fileName, ".", true);
                String name = StrUtil.subBefore(fileName, ".", true);
                //新文件名称
                String newName = uid + "." + fileSuffix;
                //上传文件
                ResultBody resultBody = FileUtils.uploadFile(file, newName, fileUploadPath);
                if (!resultBody.isOk()) {
                    return ResultBody.failed("文件上传失败");
                }
                if(!fileUploadRelative.endsWith("/")){
                    fileUploadRelative = fileUploadRelative+"/";
                }
                String url = fileUploadRelative +  newName;
                // 计算文件大小kb
                long fileSizeKb = Convert.toLong(NumberUtil.div(new BigDecimal(file.getSize()), BigDecimal.valueOf(1024)).setScale(0, BigDecimal.ROUND_HALF_UP));
                fileInfo = FileInfo.builder()
                        .fileName(name)
                        .nameCode(uid)
                        .fileSuffix(fileSuffix)
                        .filePath(StrUtil.toString(resultBody.getData()))
                        .status("0")
                        .fileSize(fileSizeKb)
                        .createdTime(new Date())
                        .previewAddress(url)
                        .build();
                //保存文件上传记录
                fileInfoService.saveAndUpdate(fileInfo);
            } catch (Exception e) {
                log.error("上传文件失败：{}",e.getMessage());
            }
        }
        log.info("上传文件结束!");
        return ResultBody.success(fileInfo);
    }

}
